import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;


import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class ShpfileReader {
    //返回shp数据的SimpleFeatureCollection对象
    //再由工具类将对象的数据导入到PostGIS中

    public String getShpTypeName() {
        return shpTypeName;
    }

    static String shpTypeName="";
    /**
     * 读取所选择的shp文件内容
     * @param pPath shp文件的绝对路径
     * @return
     * @throws Exception
     */
    public static SimpleFeatureCollection getShpfileData(String pPath) throws Exception {
        File lpSource = new File(pPath);
        Map<String, Object> lpMapParms = new HashMap<String, Object>();
        lpMapParms.put("url", lpSource.toURI().toURL());
        DataStore lpDataStoreShp = DataStoreFinder.getDataStore(lpMapParms);
        //字符转码，防止中文乱码
        ((ShapefileDataStore) lpDataStoreShp).setCharset(Charset.forName("utf8"));
        String lpTypeName = lpDataStoreShp.getTypeNames()[0];
        SimpleFeatureSource lpFeaSource = lpDataStoreShp.getFeatureSource(lpTypeName);
        shpTypeName = lpTypeName;
        return lpFeaSource.getFeatures();
    }

    public static SimpleFeatureSource getShpfile2(String pPath,String nameCharset) throws Exception {
        File lpSource = new File(pPath);
        Map<String, Object> lpMapParms = new HashMap<String, Object>();
        lpMapParms.put("url", lpSource.toURI().toURL());
        DataStore lpDataStoreShp = DataStoreFinder.getDataStore(lpMapParms);
        //字符转码，防止中文乱码
        ((ShapefileDataStore) lpDataStoreShp).setCharset(Charset.forName(nameCharset));
        String lpTypeName = lpDataStoreShp.getTypeNames()[0];
        SimpleFeatureSource lpFeaSource = lpDataStoreShp.getFeatureSource(lpTypeName);
        shpTypeName = lpTypeName;
        return lpFeaSource;
    }
}
